<template>
  <div class="content">
    <div class="search">
      <span>高级搜索</span>
    </div>
    <el-form ref="form" label-position="top" label-width="80px" style="margin-top: 27px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="合同编号">
            <el-input
              clearable
              v-model="pageParams.contractNo"
              style="width: 257px"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="客户姓名">
            <el-input
              clearable
              v-model="pageParams.name"
              style="width: 257px"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="手机号">
            <el-input
              clearable
              v-model="pageParams.phone"
              style="width: 257px"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="购买学科">
            <el-select
              clearable
              v-model="pageParams.subjectName"
              style="width: 257px"
              placeholder="请选择"
            >
              <el-option v-for="item in selectList" :key="item.id" :value="item.subjectName">{{
                item.subjectName
              }}</el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="购买课程">
            <el-select
              clearable
              v-model="pageParams.courseName"
              style="width: 257px"
              placeholder="请选择"
            >
              <el-option v-for="item in selectList" :key="item.id" :value="item.courseName">{{
                item.courseName
              }}</el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="创建时间">
            <div class="block">
              <el-date-picker
                v-model="pageParams.createTime"
                type="datetimerange"
                :shortcuts="shortcuts"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: 237px"
              />
            </div>
          </el-form-item>
        </el-col>
        <el-col
          :span="11"
          type="flex"
          justify="end"
          style="margin-top: 25px; display: flex; justify-content: end"
        >
          <el-form-item>
            <el-button
              style="
                border-radius: 30px;
                background-color: #05cc95;
                color: #fff;
                width: 92px;
                height: 40px;
              "
              @click="search"
              >搜索</el-button
            >
            <el-button
              style="border-radius: 30px; background-color: #eaeaea; width: 92px; height: 40px"
              @click="reset"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row style="display: flex; justify-content: space-between; margin-top: 30px">
      <div style="margin-top: 11px">
        已选<span style="color: #75dfc3"> {{ pageParams.total }} </span>项
      </div>
      <el-button
        size="large"
        style="border-radius: 30px; margin-right: 50px; background-color: #fd7065; color: #fff"
        @click="append"
        >添加合同</el-button
      >
    </el-row>

    <el-table :data="list" style="margin-top: 35px">
      <el-table-column label="序号" width="80px" type="index"> </el-table-column>
      <el-table-column prop="contractNo" label="合同编号"></el-table-column>
      <el-table-column prop="name" label="客户姓名"></el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <el-table-column prop="subjectName " label="购买学科"></el-table-column>
      <el-table-column prop="courseName" label="购买课程"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button type="text" size="small" @click="Preview(row.id)">预览</el-button>
          <el-button
            type="text"
            size="small"
            style="padding: 0px; margin: 0px"
            @click="Details(row.id)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        v-model:current-page="pageParams.pageNum"
        v-model:page-size="pageParams.pageSize"
        :page-sizes="[1, 10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageParams.total"
        @change="onChange"
        :show-total="(total) => `共 ${total} 条`"
        show-size-changer
        show-quick-jumper
      />
    </div>
  </div>
  <div class="box">
    <el-dialog title="添加合同" style="width: 620px" v-model="showDiaLog">
      <el-form
        ref="form"
        :model="formData"
        :rules="rules"
        label-position="top"
        style="padding: 30px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item prop="name" label="客户姓名">
              <el-input
                v-model="formData.name"
                size="large"
                style="width: 245px"
                placeholder="请输入客户姓名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="display: flex; justify-content: end">
            <el-form-item prop="phone" label="客户手机号">
              <el-input
                v-model="formData.phone"
                size="large"
                style="width: 245px"
                placeholder="请输入客户手机号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="contractNo" label="合同编号">
              <el-input
                v-model="formData.contractNo"
                size="large"
                style="width: 245px"
                placeholder="请输入合同编号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="display: flex; justify-content: end">
            <el-form-item prop="subjectName" label="购买学科">
              <el-select
                v-model="formData.subjectName"
                size="large"
                style="width: 245px"
                placeholder="请选择购买学科"
              >
                <el-option v-for="item in selectLists" :key="item.id" :value="item.subjectName">{{
                  item.subjectName
                }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="courseName" label="购买课程">
              <el-select
                v-model="formData.courseName"
                size="large"
                style="width: 245px"
                placeholder="请选择购买课程"
              >
                <el-option v-for="item in selectLists" :key="item.id" :value="item.courseName">{{
                  item.courseName
                }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="display: flex; justify-content: end">
            <el-form-item prop="channelSource" label="渠道来源">
              <el-select
                v-model="formData.channelSource"
                size="large"
                style="width: 245px"
                placeholder="请输入渠道来源"
              >
                <el-option label="线上活动" value="线上活动"></el-option>
                <el-option label="推广介绍" value="推广介绍"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="active" label="活动信息">
              <el-select
                v-model="formData.active"
                size="large"
                style="width: 245px"
                placeholder="请选择活动信息"
              >
                <el-option label="课程折扣" value="课程折扣"></el-option>
                <el-option label="课程代金券" value="课程代金券"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <div style="display: flex">
          <span style="margin-top: 12px">上传合同</span>
          <el-upload
            v-model:file-list="fileList"
            action="/api/contract/upload"
            multiple
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="3"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            accept=".pdf"
            prop="url"
          >
            <el-button
              style="width: 108px; height: 40px; border-radius: 20px; margin-left: 40px"
              icon="UploadFilled"
              type="primary"
              @click="upload"
              v-model="formData.url"
              >上传</el-button
            >
          </el-upload>
        </div>

        <el-col style="display: flex; justify-content: end">
          <el-form-item>
            <el-button style="width: 95px; height: 40px; border-radius: 20px" @click="btnCancel"
              >取消</el-button
            >
            <el-button
              style="width: 95px; height: 40px; border-radius: 20px"
              type="primary"
              @click="btnOK"
              >确定</el-button
            >
          </el-form-item>
        </el-col>
      </el-form>
    </el-dialog>

    <el-dialog
      title="预览合同"
      v-model="isShow"
      style="padding: 35px 50px; width: 1215px"
      :before-close="handleDialogClose"
    >
      <el-divider />

      <div>{{ contractContent }}</div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getContractList, addContract, getContractPreview } from '@/api/contractManagement'
import { useRouter } from 'vue-router'

// import { setList } from '@/utils/auth'
import { ElButton, ElUpload, ElMessage, ElMessageBox } from 'element-plus'
const contractContent = ref('') // 合同内容

let router = useRouter()
const showDiaLog = ref(false)
const append = () => {
  showDiaLog.value = true
}
const isShow = ref(false)
const selectList = ref([])
const selectLists = ref([])

const list = ref([])
const pageParams = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  courseTitle: ''
})
const btnOK = async () => {
  const res = await addContract(formData.value)
  console.log(res)
  ElMessage.success('添加成功')
  getContractListAPI()
  showDiaLog.value = false
  //重置表单
  formData.value = {
    name: '',
    phone: '',
    contractNo: '',
    subjectName: '',
    courseName: '',
    channelSource: '',
    active: '',
    url: ''
  }
}
const getContractListAPI = async () => {
  const res = await getContractList(pageParams.value)
  console.log(res.records)
  list.value = res.records
  selectList.value = res.records
  selectLists.value = res.records

  pageParams.value.total = res.total

  //时间戳转为时间
  list.value.forEach((item) => {
    const date = new Date(item.createTime)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    item.createTime = `${year}-${'0' + month}-${day}`
    const date1 = new Date(item.endTime)
    const year1 = date1.getFullYear()
    const month1 = date1.getMonth() + 1
    const day1 = date1.getDate()
    item.endTime = `${year1}-${'0' + month1}-${day1}`
  })
}
onMounted(() => {
  getContractListAPI()
})
//上传文件的列表
const fileList = ref([])
//上传合同

const handleRemove = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}
const handlePreview = (uploadFile) => {
  console.log(uploadFile)
}
const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  )
}
const beforeRemove = (uploadFile) => {
  return ElMessageBox.confirm(`是否取消传输 ${uploadFile.name} ?`).then(
    () => '确认',
    () => '取消'
  )
}
const beforeUpload = (file) => {
  const isLt2 = file.size / 1024 / 1024 < 2
  if (!isLt2) {
    ElMessage.error(`上传文件大小不能超过 2MB`)
    return false
  }
  return true
}
const handleUploadSuccess = (response, file, uploadFiles) => {
  console.log(response.data, file, uploadFiles)
  formData.value.url = response.data
  ElMessage.success('上传成功')
}
const handleUploadError = (err, file, uploadFiles) => {
  console.log(err, file, uploadFiles)
  ElMessage.error('上传失败')
}

// const Preview = async(id) => {
//   isShow.value = true
//   const res = await getContractPreview(id)
//   console.log(res);
//   const fileUrl = res.data.fileUrl;

// }

const handleDialogClose = () => {
  contractContent.value = ''
}

// 预览合同
const Preview = async (id) => {
  // 获取合同内容
  try {
    const res = await getContractPreview(id)
    console.log(res)

    const fileContent = res?.data?.fileContent

    if (fileContent) {
      window.open(fileContent, '_blank')
    } else {
      throw new Error('合同内容为空')
    }
  } catch (error) {
    console.error('预览合同失败', error)
    ElMessage.error('预览合同失败')
  }
}
//表单校验规则
const rules = ref({
  name: [{ required: true, message: '客户姓名不能为空', trigger: 'blur' }],
  phone: [
    { required: true, message: '客户手机号不能为空', trigger: 'blur' },
    { min: 11, max: 11, message: '手机号格式不正确', trigger: 'blur' }
  ],
  contractNo: [{ required: true, message: '合同编号不能为空', trigger: 'blur' }],
  subjectName: [{ required: true, message: '购买学科不能为空', trigger: 'blur' }],
  courseName: [{ required: true, message: '购买课程不能为空', trigger: 'blur' }],
  channelSource: [{ required: true, message: '渠道来源不能为空', trigger: 'blur' }],
  active: [{ required: true, message: '活动信息不能为空', trigger: 'blur' }],
  url: [{ required: true, message: '合同不能为空', trigger: 'blur' }]
})
//添加合同弹出框表单数据
const formData = ref({
  name: '',
  phone: '',
  contractNo: '',
  subjectName: '',
  courseName: '',
  channelSource: '',
  active: '',
  url: ''
})

//搜索
const search = () => {
  getContractListAPI(pageParams.value)
}
const onChange = (pageNum, pageSize) => {
  pageParams.value.pageNum = pageNum
  pageParams.value.pageSize = pageSize
  getContractListAPI(pageParams.value)
}

//取消
const btnCancel = () => {
  showDiaLog.value = false
  //重置表单
  formData.value = {
    name: '',
    phone: '',
    contractNo: '',
    subjectName: '',
    courseName: '',
    channelSource: '',
    active: '',
    url: ''
  }
}
//跳转页面
const Details = (id) => {
  console.log(id)
  router.push({
    path: '/details',
    query: {
      id
    }
  })
}

//重置表单
const reset = () => {
  pageParams.value = {
    pageNum: 1,
    pageSize: 10,
    total: 0,
    courseTitle: ''
  }

  getContractListAPI()
}
</script>

<style lang="scss" scoped>
.content {
  width: 100%;
  height: 100vh;
  background-color: #fff;
  padding: 28px 0px 0px 32px;
}
.search {
  height: 45px;
  background-color: #f2f2f2;
  span {
    line-height: 45px;
    margin-left: 32px;
    font-style: 16px;
    font-weight: 700;
  }
}
.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
.box {
  :deep(.el-dialog__header) {
    background-color: #1890ff;
  }
  :deep(.el-dialog__title) {
    color: #fff;
  }
  :deep(.el-icon) {
    color: #797979;
    font-size: 20px;
  }
}
:deep(.el-input__wrapper) {
  border-radius: 10px;
  background-color: #f9f9f9;
}
</style>
